﻿using System;
using System.Collections.Generic;
using offline2048;
using com.adjust.sdk;
using MotionFramework.Console;
using UnityEngine;
// ReSharper disable InconsistentNaming

namespace GTA
{

    public class AdWrapper : MonoSingleton<AdWrapper>
    {
        /*private string[] BANNER_ID = { "" };
        private string[] INTERSTITIAL_ID = { "" };*/

#if UNITY_IOS
        private const string InterstitialAdUnitId = "c234928578d78235";
        private const string RewardedAdUnitId = "bc1f2becf62e9b18";
        private const string RewardedInterstitialAdUnitId = "ENTER_IOS_REWARD_INTER_AD_UNIT_ID_HERE";
        private const string BannerAdUnitId = "dcd3588b622adb82";
        private const string MRecAdUnitId = "ENTER_IOS_MREC_AD_UNIT_ID_HERE";
#else // UNITY_ANDROID
        private const string InterstitialAdUnitId = "5425b84dfad47932";
        private const string RewardedAdUnitId = "f309ce11e27fe48e";
        private const string RewardedInterstitialAdUnitId = "ENTER_ANDROID_REWARD_INTER_AD_UNIT_ID_HERE";
        private const string BannerAdUnitId = "e34f84e16268cfa0";
        private const string MRecAdUnitId = "ENTER_ANDROID_MREC_AD_UNIT_ID_HERE";
#endif
        
        private bool _bannerShow = false;
        private Action<bool> _rewardCallback = null;
        private bool _isRequestRewardedVideo = false;
        public string netWorkName = "";

        ///广告缓存 相关参数
        private Dictionary<string, string> _cachedInterstitialWorkName = new Dictionary<string, string>();
        private int _requestINIndex = 0;
        private Dictionary<string, string> _cachedRewardNetWorkName = new Dictionary<string, string>();
        private int _requestRDIndex = 0;
        public string BannerNetWorkName = "";

        private int m_InterstitialRetryAttempt = 0;
        private int m_RewardedRetryAttempt = 0;
        private bool m_isInited = false;
        
        public void Init()
        {
            MaxSdkCallbacks.OnSdkInitializedEvent += (MaxSdkBase.SdkConfiguration sdkConfiguration) =>
            {
                GameLogger.LogError("MaxSdk init ok");
                /*InitializeInterstitialAds();
                InitializeRewardedAds();
                InitializeBannerAds();*/
                m_isInited = true;
                OnEnable();
                //MaxSdk.ShowMediationDebugger();
                ADSHelper.ShowBannerAd();
            };
            m_isInited = false;
            string s1 =
                "ImJXZm5VWjQwZTRMVjhjUHJiX3ZjQ283YXZPc21JcVhSOXlkZmlpQXBBOGl";
            string s2 =
                "EX1hUVHpXUnkwaFg3WmQ5YmNnY1dPc3l1Ul9jeG1FRVV0Y1NjYU12V2hDIg==";
            string s3 = s1 + s2;

            string s4 = MainManager.Instance.Base64ToString(s3);
            MaxSdk.SetSdkKey(s4);
            //MaxSdk.SetSdkKey("bWfnUZ40e4LV8cPrb_vcCo7avOsmIqXR9ydfiiApA8iD_XTTzWRy0hX7Zd9bcgcWOsyuR_cxmEEUtcScaMvWhC");
            MaxSdk.InitializeSdk();
        }

        private void OnEnable()
        {
            if(m_isInited)
            {
                //AdsManager.OnSdkInitializedEvent += OnSDKInited;
                //banner
                MaxSdkCallbacks.Banner.OnAdLoadedEvent += OnAdLoadedEvent;
                MaxSdkCallbacks.Banner.OnAdLoadFailedEvent += OnAdFailedEvent;
                MaxSdkCallbacks.Banner.OnAdClickedEvent += OnAdClickedEvent;
                MaxSdkCallbacks.Banner.OnAdRevenuePaidEvent += OnAdPaidEvent;
                //Interstitial
                MaxSdkCallbacks.Interstitial.OnAdLoadedEvent += OnInterstitialLoadedEvent;
                MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent += OnInterstitialFailedEvent;
                MaxSdkCallbacks.Interstitial.OnAdDisplayedEvent += OnInterstitialOpenedEvent;
                //AdsManager.OnInterstitialAdFullScreenContentOpenedEvent += OnInterstitialOpenedEvent;
                MaxSdkCallbacks.Interstitial.OnAdHiddenEvent += OnInterstitialClosedEvent;
                //AdsManager.OnInterstitialAdImpressionRecordedEvent += OnInterstitialShownEvent;
                MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent += OnInterstitialPlayFailedEvent;
                //MaxSdkCallbacks.Interstitial.OnInterstitialClickedEvent += OnInterstitialClickedEvent;
                MaxSdkCallbacks.Interstitial.OnAdRevenuePaidEvent += OnInterstitialPaidEvent;
                //RewardedVideo
                MaxSdkCallbacks.Rewarded.OnAdLoadedEvent += OnRewardedVideoLoadedEvent;
                MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent += OnRewardedVideoFailedEvent;
                // AdsManager.OnRewardedVideoImpressionRecordedEvent += OnRewardedVideoShownEvent;
                MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent += OnRewardedVideoShownEvent;
                MaxSdkCallbacks.Rewarded.OnAdClickedEvent += OnRewardedVideoClickedEvent;
                MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent += OnRewardedVideoFailedToPlayEvent;
                MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent += OnRewardedVideoReceivedRewardEvent;
                MaxSdkCallbacks.Rewarded.OnAdHiddenEvent += OnRewardedVideoClosedEvent;
                MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnRewardedVideoPaidEvent;
                /*AdsManager.OnAdImpressionTrackedEventBg += OnImpressionTrackedEventBg;
                AdsManager.OnInterstitialImpressionTrackedEventBg += OnInterstitialImpressionTrackedEventBg;
                AdsManager.OnRewardedVideoImpressionTrackedEventBg += OnRewardAdImpressionTrackedEventBg;*/
                // Load the first interstitial
                LoadInterstitial();
                // Load the first RewardedAd
                LoadRewardedAd();
                // Banners are automatically sized to 320x50 on phones and 728x90 on tablets.
                // You may use the utility method `MaxSdkUtils.isTablet()` to help with view sizing adjustments.
                MaxSdk.CreateBanner(BannerAdUnitId, MaxSdkBase.BannerPosition.BottomCenter);

                // Set background or background color for banners to be fully functional.
                MaxSdk.SetBannerBackgroundColor(BannerAdUnitId, Color.black);
            }
        }

        private void OnDisable()
        {
            //AdsManager.OnSdkInitializedEvent -= OnSDKInited;
            //banner
            MaxSdkCallbacks.Banner.OnAdLoadedEvent -= OnAdLoadedEvent;
            MaxSdkCallbacks.Banner.OnAdLoadFailedEvent -= OnAdFailedEvent;
            MaxSdkCallbacks.Banner.OnAdClickedEvent -= OnAdClickedEvent;
            MaxSdkCallbacks.Banner.OnAdRevenuePaidEvent -= OnAdPaidEvent;
            //Interstitial
            MaxSdkCallbacks.Interstitial.OnAdLoadedEvent -= OnInterstitialLoadedEvent;
            MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent -= OnInterstitialFailedEvent;
            //AdsManager.OnInterstitialAdFullScreenContentOpenedEvent -= OnInterstitialOpenedEvent;
            MaxSdkCallbacks.Interstitial.OnAdHiddenEvent -= OnInterstitialClosedEvent;
            //AdsManager.OnInterstitialAdImpressionRecordedEvent -= OnInterstitialShownEvent;
            MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent -= OnInterstitialPlayFailedEvent;
            //AdsManager.OnInterstitialClickedEvent -= OnInterstitialClickedEvent;
            MaxSdkCallbacks.Interstitial.OnAdRevenuePaidEvent -= OnInterstitialPaidEvent;
            //RewardedVideo
            MaxSdkCallbacks.Rewarded.OnAdLoadedEvent -= OnRewardedVideoLoadedEvent;
            MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent -= OnRewardedVideoFailedEvent;
            // AdsManager.OnRewardedVideoImpressionRecordedEvent -= OnRewardedVideoShownEvent;
            MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent -= OnRewardedVideoShownEvent;
            MaxSdkCallbacks.Rewarded.OnAdClickedEvent -= OnRewardedVideoClickedEvent;
            MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent -= OnRewardedVideoFailedToPlayEvent;
            MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent -= OnRewardedVideoReceivedRewardEvent;
            MaxSdkCallbacks.Rewarded.OnAdHiddenEvent -= OnRewardedVideoClosedEvent;
            MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent -= OnRewardedVideoPaidEvent;
            
            /*AdsManager.OnAdImpressionTrackedEventBg -= OnImpressionTrackedEventBg;
            AdsManager.OnInterstitialImpressionTrackedEventBg -= OnInterstitialImpressionTrackedEventBg;
            AdsManager.OnRewardedVideoImpressionTrackedEventBg -= OnRewardAdImpressionTrackedEventBg;*/
        }

        void OnSDKInited()
        {

        }

        /*private void OnImpressionTrackedEventBg(string adUnitId,ResponseInfo responseInfo)
        {
            netWorkName = responseInfo.GetMediationAdapterClassName();
            if (string.IsNullOrEmpty(netWorkName))
            {
                netWorkName = "empty";
            }
            int type = 3;

            //记录渠道名
            BannerNetWorkName = netWorkName;
            AdsDataMgr.Instance.SaveData();
        }*/
        
        /*private void OnInterstitialImpressionTrackedEventBg(string adUnitId,ResponseInfo responseInfo)
        {
            netWorkName = responseInfo.GetMediationAdapterClassName();
            if (string.IsNullOrEmpty(netWorkName))
            {
                netWorkName = "empty";
            }
            int type = 2;
            ADSPlayData adsPlayData = new ADSPlayData();
            adsPlayData.adType = type;
            adsPlayData.Adid = adUnitId;
            adsPlayData.Network = netWorkName;
            adsPlayData.InterstitialGameState = AdsDataMgr.Instance.GetAdFireScene(AdsDataMgr.EAdDebugType.Interstitial);
            adsPlayData.DateTime = DateTime.UtcNow;
            DataSaveHelper.Instance.Add(ADSHelper.ACTION_TYPE, Newtonsoft.Json.JsonConvert.SerializeObject(adsPlayData));

            GameLogger.Log(MotionFramework.Console.GameLogType.ADS, 
                "[thread] adType:" + adsPlayData.adType
                + "\r\n\tAdid:" + adsPlayData.Adid
                    // + "\r\n\tFormat:" + adsPlayData.Format
                + "\r\n\tNetwork:" + adsPlayData.Network
                + "\r\n\tInterstitialGameState:" + adsPlayData.InterstitialGameState
                + "\r\n\tDateTime:" + adsPlayData.DateTime.ToString());

            GameLauncherEx.Instance.AddMainAction(() =>
            {
                GameLogger.Log(MotionFramework.Console.GameLogType.ADS,
                    "[main] adType:" + adsPlayData.adType
                    + "\r\n\tAdid:" + adsPlayData.Adid
                        // + "\r\n\tFormat:" + adsPlayData.Format
                    + "\r\n\tNetwork:" + adsPlayData.Network
                    + "\r\n\tInterstitialGameState:" + adsPlayData.InterstitialGameState
                    + "\r\n\tDateTime:" + adsPlayData.DateTime.ToString()); 
            });

            //记录渠道名
            AdsDataMgr.Instance.SetAdNetwork(AdsDataMgr.EAdDebugType.Interstitial, netWorkName);
            if (_cachedInterstitialWorkName == null)
            {
                _cachedInterstitialWorkName = new Dictionary<string, string>();
            }
            if (!_cachedInterstitialWorkName.ContainsKey(adUnitId))
            {
                _cachedInterstitialWorkName.Add(adUnitId, netWorkName);
            }
            else
            {
                _cachedInterstitialWorkName[adUnitId] = netWorkName;
            }
            AdsDataMgr.Instance.SaveData();
        }
        
        private void OnRewardAdImpressionTrackedEventBg(string adUnitId,ResponseInfo responseInfo)
        {
            netWorkName = responseInfo.GetMediationAdapterClassName();
            if (string.IsNullOrEmpty(netWorkName))
            {
                netWorkName = "empty";
            }
            int type = 1;
            ADSPlayData adsPlayData = new ADSPlayData();
            adsPlayData.adType = type;
            adsPlayData.Adid = adUnitId;
            adsPlayData.Network = netWorkName;
            adsPlayData.InterstitialGameState = AdsDataMgr.Instance.GetAdFireScene(AdsDataMgr.EAdDebugType.RewardVideo);
            adsPlayData.DateTime = DateTime.UtcNow;
            DataSaveHelper.Instance.Add(ADSHelper.ACTION_TYPE, Newtonsoft.Json.JsonConvert.SerializeObject(adsPlayData));

            GameLogger.Log(MotionFramework.Console.GameLogType.ADS, 
                "[thread] adType:" + adsPlayData.adType
                + "\r\n\tAdid:" + adsPlayData.Adid
                    // + "\r\n\tFormat:" + adsPlayData.Format
                + "\r\n\tNetwork:" + adsPlayData.Network
                + "\r\n\tInterstitialGameState:" + adsPlayData.InterstitialGameState
                + "\r\n\tDateTime:" + adsPlayData.DateTime.ToString());

            GameLauncherEx.Instance.AddMainAction(() =>
            {
                GameLogger.Log(MotionFramework.Console.GameLogType.ADS,
                    "[main] adType:" + adsPlayData.adType
                    + "\r\n\tAdid:" + adsPlayData.Adid
                        // + "\r\n\tFormat:" + adsPlayData.Format
                    + "\r\n\tNetwork:" + adsPlayData.Network
                    + "\r\n\tInterstitialGameState:" + adsPlayData.InterstitialGameState
                    + "\r\n\tDateTime:" + adsPlayData.DateTime.ToString()); 
            });

            //记录渠道名
            AdsDataMgr.Instance.SetAdNetwork(AdsDataMgr.EAdDebugType.RewardVideo, netWorkName);
            if (_cachedRewardNetWorkName == null)
            {
                _cachedRewardNetWorkName = new Dictionary<string, string>();
            }
            if (!_cachedRewardNetWorkName.ContainsKey(adUnitId))
            {
                _cachedRewardNetWorkName.Add(adUnitId, netWorkName);
            }
            else
            {
                _cachedRewardNetWorkName[adUnitId] = netWorkName;
            }
            AdsDataMgr.Instance.SaveData();
        }*/
        
        private static string GetAdTypeName(int type)  {
            switch (type)
            {
                case 0:
                    return "Banner";
                case 1:
                    return "Interstitial";
                case 2:
                    return "Rewarded Video";
                default:
                    return "unknown";
            }
        }

        public void OnAdRequestBeginCallback(int type, string adUnitId)
        {
            // GameLogger.Log(MotionFramework.Console.GameLogType.ADS, 
            //     "[thread] [JoyCastle] Start Request Ad, adType:" + GetAdTypeName(type) + " adUnitId:" + adUnitId);
        }

        public void OnAdRequestEndCallback(int type, string adUnitId)
        {
            // GameLogger.Log(MotionFramework.Console.GameLogType.ADS, 
            //     "[thread] [JoyCastle] Ad Loaded. adType:" + GetAdTypeName(type) + " adUnitId:" + adUnitId);
        }

        #region ----------banner-----------

        public void showBannerAd()
        {    
            if (_bannerShow) return;
                
            _bannerShow = true;

            MaxSdk.ShowBanner(BannerAdUnitId);
        }

        public void hideBannerAd()
        { 
            // if (!_bannerShow) return;
                
            _bannerShow = false;

            MaxSdk.HideBanner(BannerAdUnitId);
        }

        /*private bool isBannerAvailable()
        {
            return AdsManager.Instance.IsBannerLoaded();
        }*/

        private void OnAdLoadedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            ADSHelper.Instance.onBannerLoaded();
            Debug.Log("[JoyCastle][Unity] MoPubWrapper  OnAdLoadedEvent:" + adUnitId);
        }

        private void OnAdFailedEvent(string adUnitId,MaxSdkBase.ErrorInfo adInfo)
        {
            ADSHelper.Instance.onBannerLoadFailed();
        }

        private void OnAdClickedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            ADSHelper.Instance.onBannerClicked();
        }

        private void OnAdPaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
        {
            
            ADSHelper.Instance.onBannerPaid();
        }

        #endregion

        #region ---------Interstitial----------
        public string GetInterstitialWorkName()
        {
            var id = AdsDataMgr.Instance.AdInterstitialID;
            if (_cachedInterstitialWorkName == null || string.IsNullOrEmpty(id))
            {
                return "empty";
            }

            return _cachedInterstitialWorkName.ContainsKey(id) ? _cachedInterstitialWorkName[id] : "empty";
        }

        public void showInterstitialAd()
        {
            /*var adId = AdsManager.Instance.ShowInterstitialAd();
            if (adId.Length != 0)
            {
                //记录插屏广告的播放ID
                AdsDataMgr.Instance.AdInterstitialID = adId;
                AdsDataMgr.Instance.SaveData();
            }
            else
            {
                GameLogger.Log(GameLogType.ADS,$"AdWrapper - showInterstitialAd {adId}");
            }
            _rewardCallback = null; */
            if (MaxSdk.IsInterstitialReady(InterstitialAdUnitId))
            {
                MaxSdk.ShowInterstitial(InterstitialAdUnitId);
            }
            else
            {
                GameLogger.LogError("Interstitial Ad not ready");
            }

            _rewardCallback = null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="callback"></param>
        /*public void showInterstitialAd(Action<Reward> callback)
        {
            var adId = AdsManager.Instance.ShowInterstitialAd();
            if (adId.Length != 0)
            {
                //记录插屏广告的播放ID
                AdsDataMgr.Instance.AdInterstitialID = adId;
                AdsDataMgr.Instance.SaveData();
                _rewardCallback = callback; 
            }
            else
            {
                GameLogger.Log(GameLogType.ADS,$"AdWrapper - showInterstitialAd {adId}");
            }  
        }*/

        public bool isInterstitiaAvailable()
        {
            return MaxSdk.IsInterstitialReady(InterstitialAdUnitId);
        }

        private void OnInterstitialLoadedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            GameLogger.LogError("插屏播放 ==========" + adInfo.NetworkName);

            ADSHelper.Instance.onInterstitialLoaded();
            m_InterstitialRetryAttempt = 0;
        }

        private void OnInterstitialFailedEvent(string adUnit,MaxSdkBase.ErrorInfo errorInfo)
        {
            m_InterstitialRetryAttempt++;
            double retryDelay = Math.Pow(2, Math.Min(6, m_InterstitialRetryAttempt));
            ADSHelper.Instance.onInterstitialLoadFailed();
            
            Invoke("LoadInterstitial", (float) retryDelay);
        }
        
        private void LoadInterstitial()
        {
            MaxSdk.LoadInterstitial(InterstitialAdUnitId);
        }
        
        /// <summary>
        /// 插屏打开
        /// </summary>
        /// <param name="adUnitId"></param>
        private void OnInterstitialOpenedEvent(string adUnitId,MaxSdkBase.AdInfo info)
        {
            DataPointTools.Instance.AddShowInterstitialAdTimes();
            ADSHelper.Instance.onInterstitialOpened(adUnitId);
        }
        
        /// <summary>
        ///插屏关闭
        /// </summary>
        /// <param name="adUnitId"></param>
        private void OnInterstitialClosedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            //_interstitialAvailable = false;
            //DataSaveHelper.Instance.CleanKey(ADSHelper.ACTION_TYPE);
            GameLogger.Log(MotionFramework.Console.GameLogType.ADS, "clean");
            ADSHelper.Instance.onInterstitialClosed();
            GameLogger.LogError("===OnInterstitialClosedEvent=============");
            LoadInterstitial();
        }
        
        /// <summary>
        /// 插屏展示
        /// </summary>
        /// <param name="adUnitId"></param>
        private void OnInterstitialShownEvent(string adUnitId)
        {
            
        }
        
        /// <summary>
        /// 插屏播放失败
        /// </summary>
        /// <param name="adUnitId"></param>
        private void OnInterstitialPlayFailedEvent(string adUnitId,MaxSdkBase.ErrorInfo errorInfo, MaxSdkBase.AdInfo adInfo)
        {
            GameLogger.Log("Interstitial failed to display with error code: " + errorInfo.Code);
            LoadInterstitial();
        }


        /// <summary>
        /// 插屏展示
        /// </summary>
        /// <param name="adUnitId"></param>
        private void OnInterstitialClickedEvent(string adUnitId)
        {
            ADSHelper.Instance.onInterstitialClicked();
        }
        
        /// <summary>
        /// 插屏获得收入
        /// </summary>
        private void OnInterstitialPaidEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            GameLogger.Error("OnInterstitialPaidEvent==" + adInfo.Revenue);
            ADSHelper.Instance.onInterstitiaPaid();
            if (_rewardCallback != null)
            {
                _rewardCallback.Invoke(true);
                _rewardCallback = null;
            }
            
            var adRevenue = new AdjustAdRevenue(AdjustConfig.AdjustAdRevenueSourceAppLovinMAX);
            adRevenue.setRevenue(adInfo.Revenue, "USD");
            adRevenue.setAdRevenueNetwork(adInfo.NetworkName);
            adRevenue.setAdRevenueUnit(adInfo.AdUnitIdentifier);
            adRevenue.setAdRevenuePlacement(adInfo.Placement);
            Adjust.trackAdRevenue(adRevenue);
            //AdjustWrapper.Instance.LogEventADRevenue("8qvei3", adInfo.Revenue);
            
            Dictionary<string, object> _fireBaseParam = new Dictionary<string, object>();
            _fireBaseParam.Add("price", adInfo.Revenue);
            //AnalyticsHelper.LogEvent("FIREBASE", "ml_ads_revenue", _fireBaseParam);
            AnalyticsHelper.LogEvent("FIREBASE", "ad_impression", _fireBaseParam);
            AnalyticsHelper.LogEvent("FIREBASE", "Ad_Impression_Revenue", _fireBaseParam);
        }

        /// <summary>
        /// 是否有可播放广告
        /// </summary>
        /// <returns></returns>
        /*private bool HasInterstitialCachedAd()
        {
            return AdsManager.Instance.IsInterstitialLoaded();
        }*/
        

        /// <summary>
        /// 获取需要重新加载的广告ID
        /// </summary>
        /// <returns></returns>
        /*private string GetRequestInterstitialAdId()
        {
            return INTERSTITIAL_ID[0];
        }*/


        #endregion


        #region --------RewardVideo--------
        public string GetRewardWorkName()
        {
            string id = AdsDataMgr.Instance.AdRewardVideoID;
            if (_cachedRewardNetWorkName == null || string.IsNullOrEmpty(id))
            {
                return "empty";
            }

            if (_cachedRewardNetWorkName.ContainsKey(id))
            {
                return _cachedRewardNetWorkName[id];
            }
            return "empty";
        }
        

        /// <summary>
        /// 播放任意广告位广告
        /// </summary>
        /// <param name="callback"></param>
        public void showRewardedAd(Action<bool> callback)
        {
            if (MaxSdk.IsRewardedAdReady(RewardedAdUnitId))
            {
                MaxSdk.ShowRewardedAd(RewardedAdUnitId);
                _rewardCallback = callback;
            }
            else
            {
                GameLogger.LogError("Reward Ad not ready");
                _rewardCallback = null;
            }
            /*var adId = AdsManager.Instance.ShowRewardedAd();
            
            if (adId.Length != 0)
            {
                //记录播放的激流视频广告ID
                AdsDataMgr.Instance.AdRewardVideoID = adId;
                AdsDataMgr.Instance.SaveData();
                _rewardCallback = callback;
            }
            else
            {
                GameLogger.Log(GameLogType.ADS,$"AdWrapper - showRewardedAd {adId}");
                ADSHelper.FailedPlayRV();
                _rewardCallback = null;
            }*/
        }

        public bool isRewardedVideoAvailable()
        {
            return MaxSdk.IsRewardedAdReady(RewardedAdUnitId);
        }

        /// <summary>
        /// 获取a广告位广告状态
        /// </summary>
        /// <returns></returns>
        /*public bool isRewardedVideoAvailable_A()
        {
            return GetRewardAdCached(0);
        }*/

        /// <summary>
        /// 获取b广告位广告状态
        /// </summary>
        /// <returns></returns>
        /*public bool isRewardedVideoAvailable_B()
        {
            return GetRewardAdCached(1);
        }*/

        
        /// <summary>
        /// 获取指定广告位的广告状态
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        /*private bool GetRewardAdCached(int index)
        {
            return AdsManager.Instance.IsCertainRewardAdLoaded(index);
        }*/

        /// <summary>
        /// 修改广告缓存池状态
        /// </summary>
        /// <param name="adUnitId"></param>
        /// <param name="isLoaded"></param>
        private void ChangeRewardAdCache(string adUnitId, bool isLoaded)
        {
            // Do Nothing
        }

        private void OnRewardedVideoLoadedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            GameLogger.LogError("激励视频播放 ==========" + adInfo.NetworkName);
            //GTALogger.Log("@ OnRewardedVideoLoadedEvent." + adUnitId);
            _isRequestRewardedVideo = false;
            ChangeRewardAdCache(adUnitId, true);
            ADSHelper.Instance.onRewardedVideoAdLoaded();
            m_RewardedRetryAttempt = 0;
        }

        private void OnRewardedVideoFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
        {
            m_RewardedRetryAttempt++;
            double retryDelay = Math.Pow(2, Math.Min(6, m_RewardedRetryAttempt));
            _isRequestRewardedVideo = false;
            ChangeRewardAdCache(adUnitId, false);
            ADSHelper.Instance.onRewardedVideoAdLoadFailed(errorInfo.AdLoadFailureInfo);
            Invoke("LoadRewardedAd", (float) retryDelay);
        }

        private void OnRewardedVideoShownEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            DataPointTools.Instance.AddShowRewardAdTimes();
            ChangeRewardAdCache(adUnitId, false);
            ADSHelper.Instance.onRewardedVideoAdOpened(adUnitId);
        }

        private void OnRewardedVideoClickedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            ADSHelper.Instance.onRewardedVideoAdClicked();
        }

        private void OnRewardedVideoFailedToPlayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, MaxSdkBase.AdInfo adInfo)
        {
            //GTALogger.Log("@ OnRewardedVideoFailedToPlayEvent :" + error);
            _isRequestRewardedVideo = false;
            ChangeRewardAdCache(adUnitId, false);
            ADSHelper.Instance.onRewardedVideoAdShowFailed(errorInfo.AdLoadFailureInfo);
            LoadRewardedAd();
        }

        private void OnRewardedVideoReceivedRewardEvent(string adUnitId,  MaxSdk.Reward reward, MaxSdkBase.AdInfo adInfo)
        {
            var message = new GTAEventDefine.RewardedVideoWillCompleted();
            MotionFramework.Event.EventManager.Instance.SendMessage(message);
        
            if (_rewardCallback != null)
            {
                _rewardCallback.Invoke(true);
                _rewardCallback = null;
            }
            
            _isRequestRewardedVideo = false;
            ADSHelper.Instance.onRewardedVideoAdCompleted();
        }

        private void OnRewardedVideoClosedEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            //DataSaveHelper.Instance.CleanKey(ADSHelper.ACTION_TYPE);
            GameLogger.Log(MotionFramework.Console.GameLogType.ADS, "clean");
            _isRequestRewardedVideo = false;
            
            ChangeRewardAdCache(adUnitId, false);
            ADSHelper.Instance.onRewardedVideoAdClosed();

            LoadRewardedAd();
        }
        
        private void OnRewardedVideoPaidEvent(string adUnitId,MaxSdkBase.AdInfo adInfo)
        {
            ADSHelper.Instance.onRewardedVideoPaid();
            GameLogger.Error("OnRewardedVideoPaidEven==" + adInfo.Revenue);
            var adRevenue = new AdjustAdRevenue(AdjustConfig.AdjustAdRevenueSourceAppLovinMAX);
            adRevenue.setRevenue(adInfo.Revenue, "USD");
            adRevenue.setAdRevenueNetwork(adInfo.NetworkName);
            adRevenue.setAdRevenueUnit(adInfo.AdUnitIdentifier);
            adRevenue.setAdRevenuePlacement(adInfo.Placement);
            Adjust.trackAdRevenue(adRevenue);
            //AdjustWrapper.Instance.LogEventADRevenue("8qvei3", adInfo.Revenue)
            
            Dictionary<string, object> _fireBaseParam = new Dictionary<string, object>();
            _fireBaseParam.Add("price", adInfo.Revenue);
            //AnalyticsHelper.LogEvent("FIREBASE", "ml_ads_revenue", _fireBaseParam);
            
            AnalyticsHelper.LogEvent("FIREBASE", "ad_impression", _fireBaseParam);
            AnalyticsHelper.LogEvent("FIREBASE", "Ad_Impression_Revenue", _fireBaseParam);
        }

        private void LoadRewardedAd()
        {
            MaxSdk.LoadRewardedAd(RewardedAdUnitId);
        }
        
        #endregion
    }
}
